package controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;

@Controller
public class TestKill {
    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    @Autowired
    public Redisson redisson;


    @RequestMapping("kill")
    @ResponseBody
    // 只能解决一个tomcat的问题
    public synchronized String kill(){
        // 定义商品id
        String productKey = "iphone13";
        // 通过redis获得锁
        RLock lock = redisson.getLock(productKey);
        // 上锁(设置过期时间)
        lock.lock(30, TimeUnit.SECONDS);

        try {
            // 1.从redis中获取 手机的库存数量
            int phone = Integer.parseInt(stringRedisTemplate.opsForValue().get("phone"));
            // 2.判断手机的数量是否够秒杀的
            if (phone > 0) {
                phone--;
                stringRedisTemplate.opsForValue().set("phone", phone + "");
                System.out.println("库存剩余" + phone);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 释放锁
            lock.unlock();
        }
        return "over!";
    }

    @Bean
    public Redisson redisson(){
        Config config = new Config();
        // 使用单个redis服务器
        config.useSingleServer().setAddress("redis://10.5.30.50:6379").setDatabase(0);
        // 使用集群的redis服务器
        //config.useClusterServers().setScanInterval(2000).addNodeAddress("","","");
        return (Redisson) Redisson.create(config);
    }
}
